<script lang="ts" setup>
import {
  addUserApi,
  deleteUserApi,
  selectRoleListApi,
  selectUserAllApi,
  updateUserApi,
} from '@/api'
import { useCreateInput, useCreateSelect } from '@/hooks/renderHook'
import { useCreateAiction, useTableColumn } from '@/hooks/tableHooks'
import type { UserState } from '@/interfaces/api/user'
import type { DataFormType, ModalMakeType } from '@/interfaces/components'
import type { FormItem } from '@/interfaces/components/dataForm'
import store from '@/store'
import { AddSharp } from '@vicons/ionicons5'
import { NAvatar } from 'naive-ui'
import { ref, createVNode } from 'vue'
import useRequest from '@/hooks/requestHooks'

const requestUtils = useRequest()

const MODAL_FUNCTION = ref<{ node: 'add' | 'update' | ''; id: number }>({
  node: '',
  id: 0,
})

const tableData = ref<UserState[]>([])
const tableLoding = ref(false)

const searchForm = ref<null | DataFormType>(null)
const modalMakeRef = ref<null | ModalMakeType>(null)
const modalForm = ref<null | DataFormType>(null)

const dataFormOptions: Array<FormItem> = [
  {
    label: '用户名称',
    key: 'userName',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户名称',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '用户账号',
    key: 'accountNumber',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户名称',
        },
        refState: formTtem.value,
      })
    },
  },
]
const tableColumn = useTableColumn<UserState>(
  [
    {
      title: '用户名称',
      key: 'userName',
    },
    {
      title: '用户账号',
      key: 'accountNumber',
    },
    {
      title: '创建时间',
      key: 'createTime',
    },
    {
      title: '头像',
      key: 'imgUrl',
      render(row) {
        return createVNode(NAvatar, {
          size: 'large',
          src: row.imgUrl,
        })
      },
    },
    {
      title: '操作',
      key: 'make',
      render(row) {
        return useCreateAiction([
          {
            label: '编辑',
            type: 'info',
            disabled: ref(false),
            async onClick(aicItem) {
              MODAL_FUNCTION.value.node = 'update'
              MODAL_FUNCTION.value.id = row.id as number
              await modalMakeRef.value?.show()
              modalForm.value?.update(row)
            },
          },
          {
            label: '删除',
            type: 'error',
            disabled: ref(false),
            onClick(aicItem) {
              store.state.dialog?.warning({
                title: '警告',
                content: '你确定？',
                positiveText: '确定',
                negativeText: '不确定',
                onPositiveClick: async () => {
                  await deleteUserApi({ id: row.id as number })
                  getTableData()
                },
              })
            },
          },
        ])
      },
    },
  ],
  {
    align: 'center',
  }
)

const modalFormOptions: Array<FormItem> = [
  {
    label: '用户名称',
    key: 'userName',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户名称',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '用户账号',
    key: 'accountNumber',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户名称',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '用户密码',
    key: 'password',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户密码',
          type: 'password',
          showPasswordOn: 'mousedown',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '用户头像',
    key: 'imgUrl',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入用户头像地址',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '选择角色',
    key: 'roleId',
    value: ref(0),
    optionList: ref([]),
    async beforeRender(formTtem) {
      const res = await selectRoleListApi()
      if (formTtem.optionList) {
        formTtem.optionList.value = res.data.data.map((item) => {
          return {
            label: item.roleName,
            value: item.id,
          }
        })
      }
    },
    render(formTtem) {
      return useCreateSelect({
        selectpropsOptions: {
          size: 'small',
        },
        selectOptions: formTtem.optionList?.value || [],
        refState: formTtem.value,
      })
    },
  },
]

/**
 * @description: 获取表格数据
 */
const getTableData = async (
  params: { accountNumber: string; userName: string } = { accountNumber: '', userName: '' }
) => {
  requestUtils.useLoadingRequestOrIsNull<UserState>({
    loadings: tableLoding,
    state: tableData,
    axios: selectUserAllApi(params),
  })
}
getTableData()

/**
 * @description: 点击新增按钮时触发的函数
 */
const operationModal = async () => {
  MODAL_FUNCTION.value.node = 'add'
  await modalMakeRef.value?.show()
  modalForm.value?.reset()
}

/**
 * @description: 点击筛选内搜索按钮触发的函数
 */
const searchTableData = () => {
  let params = searchForm.value?.generatorParams()
  getTableData(params)
}

/**
 * @description: 点击筛选内重置按钮触发的函数
 */
const resetSearch = () => {
  searchForm.value?.reset()
}

/**
 * @description: 表单提交，新增/修改表单按钮触发的事件
 */
const confirm = () => {
  // 获取表单的参数
  let params = modalForm.value?.generatorParams()

  if (MODAL_FUNCTION.value.node === 'update') {
    updateConfirm({ ...params, id: MODAL_FUNCTION.value.id })
  } else if (MODAL_FUNCTION.value.node === 'add') {
    addConfirm(params)
  }
}

/**
 * @description: 更新事件
 */
const updateConfirm = async (params: UserState) => {
  // 验证表单
  if (modalForm.value?.validator()) {
    params.id = MODAL_FUNCTION.value.id
    await updateUserApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}

/**
 * @description: 添加事件
 */
const addConfirm = async (params: UserState) => {
  // 验证表单
  if (modalForm.value?.validator()) {
    await addUserApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}
</script>

<template lang="pug">
div(class="animate__animated animate__fadeIn animate__delay-0.7s")
  n-space(vertical)
    n-card(title="用户管理") 管理用户的账号密码，分配用户的角色
    TableBody
      template(#header) 
        TableHeader(searchContentHeight="200px" @search="searchTableData" @reset-search="resetSearch")
          template(#searchForm)
            DataForm(ref="searchForm" :form-config="{}" :options="dataFormOptions" preset="grid-item")
          template(#rightBtn)
            n-button(size="small" type="info" @click="operationModal") 新增
              template(#icon)
                n-icon
                  AddSharp
      template(#body)
        n-data-table(:single-line="false" :columns="tableColumn" :data="tableData" :loading="tableLoding" :row-key="(row: any) => row.id")
ModalMake(title="菜单控制台" ref="modalMakeRef" contentHeight="20px" @confirm="confirm")
  DataForm(ref="modalForm" :form-config="{}" :options="modalFormOptions" )

</template>
